<template>
  <div id="app">
    <header>购物车</header>
    <section>
      <shopping-cart-item
        v-for="item in data"
        :key="item.id"
        :goods="item"
      />
    </section>
    <footer>
      <div>
        <input type="checkbox" id="select-all" v-model="isAllSelected">
        <label for="select-all">全选</label>
      </div>
      <div>
        合计:
        <span>￥{{ total }}</span>
      </div>
      <div>结算({{ totalCount }})</div>
    </footer>
  </div>
</template>

<script>
import ShoppingCartItem from './components/shopping-cart-item.vue';
import eventBus from './event-bus';

export default {
  components: {
    ShoppingCartItem,
  },
  created () {
    eventBus.$emit('search');
  },
  computed: {
    data () {
      return eventBus.data;
    },
    total () {
      let sum = 0;
      for (const goods of this.data) {
        if (goods.goods_state) {
          sum += goods.goods_count * goods.goods_price;
        }
      }
      // 保留一位小数
      return sum.toFixed(1);
    },
    totalCount () {
      let sum = 0;
      for (const goods of this.data) {
        if (goods.goods_state) {
          sum += goods.goods_count;
        }
      }
      return sum;
    },
    // 是否全选
    isAllSelected: {
      // 不能改自己
      set (val) {
        this.data.forEach(goods => goods.goods_state = val);
      },
      get () {
        return this.data.every(goods => goods.goods_state);
      },
    },
  },
}
</script>

<style scoped>

</style>